package com.campusflea;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.campusflea.DateBase.UserInfo;
import com.campusflea.adapter.ProvinceAdapter;
import com.campusflea.adapter.SchoolAdapter;
import com.campusflea.config.Config;
import com.campusflea.custom.ClearWriteEditText;
import com.campusflea.entity.Province;
import com.campusflea.entity.School;
import com.campusflea.entity.SchoolList;
import com.campusflea.utils.GsonRequest;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import com.campusflea.entity.ProvinceList;

import static com.campusflea.R.drawable.rs_select_btn_gray;

public class RegisterActivity extends AppCompatActivity {

    private Button getSMS;
    private Button submit;
    private TextView find;
    private TextView login;
    private ClearWriteEditText nickname;
    private ClearWriteEditText password;
    private ClearWriteEditText phone;
    private ClearWriteEditText code;
    private TimerTask tt;
    private Timer tm;
    private int TIME = 60;
    private TextView mSelectSchool;
    /**
     * popView相关
     **/
    private View parent;
    private ListView mProvinceListView;
    private ListView mSchoolListView;
    private TextView mTitle;
    private PopupWindow mPopWindow;
    /**
     * Volley相关
     **/
    private RequestQueue mRequestQueue;
    /**
     * Adapter相关
     **/
    private ProvinceAdapter mProvinceAdapter;
    private SchoolAdapter mSchoolAdapter;
    private String provinceId;
    private static final int CODE_REPEAT = 1; //重新发送
    Handler hd = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CODE_REPEAT) {
                tm.cancel();//取消任务
                tt.cancel();//取消任务
                TIME = 60;//时间重置
                //btn_check.setText("重新发送验证码");
            }else {
                //btn_check.setText(TIME + "重新发送验证码");
            }
        }
    };
    EventHandler eh=new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data) {
            if (result == SMSSDK.RESULT_COMPLETE) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if(mSelectSchool.getText().toString()=="选择学校"){
                        toast("请选择学校");
                    }
                    else {
                        toast("验证成功");

                        String phoneStr=phone.getText().toString().trim();
                        String name = nickname.getText().toString().trim();
                        String pwd = password.getText().toString().trim();
                        UserInfo ui = new UserInfo();
                        ui.setPhone(phoneStr);
                        ui.setPassword(pwd);
                        ui.setNickname(name);
                        ui.setSchool(mSelectSchool.getText().toString());
                        ui.save(new SaveListener() {
                            @Override
                            public void done(Object o, Object o2) {

                            }

                            @Override
                            public void done(Object o, BmobException e) {
                                Toast.makeText(RegisterActivity.this,"sucess",Toast.LENGTH_LONG).show();
                            }
                            //Toast.makeText(RegisterActivity.this,"fail",Toast.LENGTH_LONG).show();


                        });
                    }
                }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){ //获取验证码成功
                    toast("获取验证码成功");
                }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//如果你调用了获取国家区号类表会在这里回调
//返回支持发送验证码的国家列表
                }
            }else{//错误等在这里（包括验证失败）
//错误码请参照http://wiki.mob.com/android-api-错误码参考/这里我就不再继续写了
                ((Throwable)data).printStackTrace();
                String str = data.toString();
                toast(str);
            }
        }
    };
    private void toast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RegisterActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Bmob.initialize(this, "36b62198745ed1900e5f1e8d55eb660d");
        SMSSDK.initSDK(this, "1df93b1c6ba2b", "64d339bf882a36ffda27ca44917ddc09");
        SMSSDK.registerEventHandler(eh); //注册短信回调
        getSMS = (Button) findViewById(R.id.reg_getcode);
        submit = (Button) findViewById(R.id.reg_button);
        find = (TextView) findViewById(R.id.reg_forget);
        login = (TextView) findViewById(R.id.reg_login);
        phone = (ClearWriteEditText) findViewById(R.id.reg_phone);
        code = (ClearWriteEditText) findViewById(R.id.reg_code);
        nickname = (ClearWriteEditText) findViewById(R.id.reg_username);
        password = (ClearWriteEditText) findViewById(R.id.reg_password);
        mSelectSchool = (TextView) findViewById(R.id.select_school);

        initPopView();
        mSelectSchool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopWindow();
            }
        });

        //获取验证短信
        getSMS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSMS.setBackground(getDrawable(rs_select_btn_gray));
                String phoneStr = phone.getText().toString().trim();
                if (!phoneStr.equals("")) {
                    SMSSDK.getVerificationCode("86", phoneStr);
                } else {
                    Toast.makeText(RegisterActivity.this, "请填写手机号", Toast.LENGTH_LONG).show();
                }
            }
        });
        //验证昵称
        nickname.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    // 此处为失去焦点时的处理内容
                    String name = nickname.getText().toString().trim();
                    if (name.equals("")) {
                        toast("请填写昵称");
                    }
                }
            }

        });
        //验证密码
        password.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    // 此处为失去焦点时的处理内容
                    String pwd = password.getText().toString().trim();
                    if (pwd.equals("")) {
                        toast("请填写密码");
                    }
                }
            }

        });
        //注册
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneStr = phone.getText().toString().trim();
                SMSSDK.submitVerificationCode("86", phoneStr, code.getText().toString());
                //Toast.makeText(RegisterActivity.this,""+SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE,Toast.LENGTH_LONG).show();
            }
        });
        //跳转登录
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        //跳转找回密码
        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterActivity.this, ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initPopView() {
        parent = this.getWindow().getDecorView();
        View popView = View.inflate(this, R.layout.view_select_province_list, null);
        mTitle = (TextView) popView.findViewById(R.id.list_title);
        mProvinceListView = (ListView) popView.findViewById(R.id.province);
        mSchoolListView = (ListView) popView.findViewById(R.id.school);
        mProvinceListView.setOnItemClickListener(itemListener);
        mSchoolListView.setOnItemClickListener(itemListener);

        mProvinceAdapter = new ProvinceAdapter(this);
        mProvinceListView.setAdapter(mProvinceAdapter);
        mSchoolAdapter = new SchoolAdapter(this);
        mSchoolListView.setAdapter(mSchoolAdapter);

        int width = getResources().getDisplayMetrics().widthPixels * 3 / 4;
        int height = getResources().getDisplayMetrics().heightPixels * 3 / 5;
        mPopWindow = new PopupWindow(popView, width, height);
        ColorDrawable dw = new ColorDrawable(0x30000000);
        mPopWindow.setBackgroundDrawable(dw);
        mPopWindow.setFocusable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);//允许在外侧点击取消

        loadProvince();

        mPopWindow.setOnDismissListener(listener);
    }

    private void showPopWindow() {
        mPopWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private void loadProvince() {
        mRequestQueue = Volley.newRequestQueue(this);
        GsonRequest<Province> request = new GsonRequest<Province>(Request.Method.POST, Config.PROVINCE_URL,
                Province.class, new Response.Listener<Province>() {
            @Override
            public void onResponse(Province response) {
                if (response.getData() != null && response.getError_code() == 0) {
                    mProvinceAdapter.setList(response.getData());
                    mProvinceAdapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }, this);
        mRequestQueue.add(request);
    }

    private void loadSchool() {
        mRequestQueue = Volley.newRequestQueue(this);
        GsonRequest<School> request = new GsonRequest<>(Request.Method.POST, Config.SCHOOL_URL + provinceId, School.class,
                new Response.Listener<School>() {
                    @Override
                    public void onResponse(School response) {
                        if (response.getData() != null && response.getError_code() == 0){
                            mSchoolAdapter.setList(response.getData());
                            mSchoolAdapter.notifyDataSetChanged();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }, this);
        mRequestQueue.add(request);
    }

    /**
     * ListView Item点击事件
     */
    AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (parent == mProvinceListView) {
                ProvinceList provinceName = (ProvinceList) mProvinceListView.getItemAtPosition(position);
                provinceId = provinceName.getProvince_id();
                mTitle.setText("选择学校");
                mProvinceListView.setVisibility(View.GONE);
                mSchoolListView.setVisibility(View.VISIBLE);
                loadSchool();
            } else if (parent == mSchoolListView) {
                SchoolList schoolName = (SchoolList) mSchoolListView.getItemAtPosition(position);
                mSelectSchool.setText(schoolName.getSchool_name());
                mPopWindow.dismiss();
            }
        }
    };

    /**
     * popWindow消失监听事件
     */
    PopupWindow.OnDismissListener listener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            mTitle.setText("选择地区");
            mProvinceListView.setVisibility(View.VISIBLE);
            mSchoolAdapter.setList(new ArrayList<SchoolList>());
            mSchoolAdapter.notifyDataSetChanged();
            mSchoolListView.setVisibility(View.GONE);
        }
    };

}
